import { app, BrowserWindow, ipcMain, dialog } from 'electron/main'
import os from 'os';
import { preloadPath } from '../config/index.js'
import checkUpdate from "../utils/updater.js";

import * as XLSX from 'xlsx'; // 确保引入 xlsx 库
import fs from 'fs'; // 从 Node.js 引入 fs 模块
import path from 'path';
import { fileURLToPath } from 'url';
import si from 'systeminformation';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const packageJsonPath = path.join(__dirname, '../package.json'); // 假设 package.json 在上一级目录
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));

export const createWindow = opitons => {
  const win = new BrowserWindow({
    width: 1440,
    height: 900,
    minHeight: 900,
    minWidth: 1440,
    show: false,
    autoHideMenuBar: true, // 隐藏菜单栏
    webPreferences: {
      nodeIntegration: true, // 允许前端使用node
      preload: preloadPath,
    },
    ...opitons,
  })

  win.on('ready-to-show', () => {
    win.show()
    checkUpdate(win, ipcMain);
  })

  // win.webContents.openDevTools();


  return win
}

// 版本号
ipcMain.handle('get-version', () => {
  return app.getVersion();
});

// 退出软件
ipcMain.handle('window-all-closed', () => {
  app.quit();
});

ipcMain.handle('get-package', () => {
  return packageJson;
});

ipcMain.on('window-reset', function () {
  app.relaunch()
  app.exit()
})


// 注册 IPC 处理程序，只需进行一次
ipcMain.handle('dialog:save', async (event, arg) => {

  const win = BrowserWindow.fromWebContents(event.sender); // 获取对应的窗口
  const filePath = await dialog.showSaveDialog(win, {
    title: '保存 Excel 文件',
    defaultPath: arg.name,
    filters: [
      { name: 'Excel Files', extensions: ['xlsx'] }
    ]
  });
  if (filePath.canceled) {
    return '取消保存'; // 用户取消了保存
  }

  const worksheet = XLSX.utils.aoa_to_sheet(arg.worksheetData);

  // 创建一个新的工作簿
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  // 导出 Excel 文件
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });

  // 保存文件
  try {
    fs.writeFileSync(filePath.filePath, Buffer.from(await blob.arrayBuffer()));
    return '保存成功'; // 文件保存成功
  } catch (error) {
    console.error('保存文件时出错:', error);
    return '保存失败'; // 文件保存失败
  }
});



const getMacAddress = () => {
  const interfaces = os.networkInterfaces();
  getHardwareSerialNumber().then(serialNumber => {
    // console.log(serialNumber);
  });
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      if (iface.family === 'IPv4' && !iface.internal) {
        return iface.mac;
      }
    }
  }
  return null; 
};

const getHardwareSerialNumber = () => {
  return si.system()
    .then(data => {
      return data.uuid;  // 获取硬件序列号
    })
    .catch(error => {
      console.error('Error fetching hardware serial number:', error);
    });
}

ipcMain.handle('get-mac-address', () => {
  return getMacAddress();
});
